﻿function AJAX_OBJ(url, callback, errorhandle, timer, retrial){

	this.xmlHttp = null;
	this.num = 0;
	this.url = url;
	this.urlParameters = "";
	this.callback = callback;
	
	this.errorhandle = errorhandle;

	this.timer = timer || 5000;
	this.timeout = -1;
	this.retrial = retrial || 1;

	this.childnodes = null;
	
}

AJAX_OBJ.prototype.createXMLHttpRequest = function(){
	var xmlh = null;
	xmlh = new XMLHttpRequest();
	return xmlh;
}

AJAX_OBJ.prototype.getInstance = function(){
	return this.createXMLHttpRequest();
}

AJAX_OBJ.prototype.requestData = function(){
	this.xmlHttp = this.getInstance();
	var request_url = this.url + this.urlParameters;
	var self = this;

	this.xmlHttp.onreadystatechange = function(){
		self.stateChanged();
	};

	this.xmlHttp.open("GET", request_url, true);
	this.xmlHttp.send(null);
	
}

AJAX_OBJ.prototype.postData = function(parm){
	this.xmlHttp = this.getInstance();
	var request_url = this.url;
	var self = this;

	this.xmlHttp.onreadystatechange = function(){
		self.stateChanged();
	};

	this.xmlHttp.open("POST", request_url, true);
	this.xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	this.xmlHttp.send(parm);
}

AJAX_OBJ.prototype.stateChanged = function(){
	if(this.xmlHttp.readyState == 4){
		if(this.xmlHttp.status == 200){
			this.callback(this.xmlHttp);
		}
		else{//error handling
			this.num++;
			this.errorhandle(this.xmlHttp.status);
			if(this.retrial != -1 && this.num < this.retrial){
				var self = this;
				clearTimeout(this.timeout);
				this.timeout = setTimeout(function(){self.requestData();}, this.timer);
			}
			else if(this.retrial == -1){
				var self = this;
				clearTimeout(this.timeout);
				this.timeout = setTimeout(function(){self.requestData();}, this.timer);
			}
		}
	}
}

AJAX_OBJ.prototype.addParameter = function(params){
	if(params.length > 0){
		this.urlParameters = "";
		for(var i = 0; i < params.length; i++){
			var curr_param = params[i];
			if(i == 0) this.urlParameters += "?" + curr_param.name + "=" + curr_param.value;
			else this.urlParameters += "&" + curr_param.name + "=" + curr_param.value;
		}
	}
}
